﻿using System;
using System.Collections.Generic;
using System.Threading;
using l1cs.server.model.Instance;
using l1cs.server.serverpackets;

namespace l1cs.server
{
    public class FishingTimeController
    {
        private static Logger _log = Logger.getLogger( typeof( FishingTimeController ).FullName );

        private static FishingTimeController _instance;
        private List<L1PcInstance> _fishingList = new List<L1PcInstance>();

        public static FishingTimeController getInstance()
        {
            if ( _instance == null )
            {
                _instance = new FishingTimeController();
            }
            return _instance;
        }

        public void threadSub( Object state )
        {
            while ( true )
            {
                Thread.Sleep( 300 );
                fishing();
            }
        }

        public void addMember( L1PcInstance pc )
        {
            if ( pc == null || _fishingList.Contains( pc ) )
            {
                return;
            }
            _fishingList.Add( pc );
        }

        public void removeMember( L1PcInstance pc )
        {
            if ( pc == null || !_fishingList.Contains( pc ) )
            {
                return;
            }
            _fishingList.Remove( pc );
        }

        private void fishing()
        {
            if ( _fishingList.Count > 0 )
            {
                long currentTime = DateTime.Now.Ticks / 10000;
                for ( int i = 0; i < _fishingList.Count; i++ )
                {
                    L1PcInstance pc = _fishingList[i];
                    if ( pc.isFishing() )
                    {
                        long time = pc.getFishingTime();
                        if ( currentTime <= ( time + 1000 )
                                && currentTime >= ( time - 1000 )
                                && !pc.isFishingReady() )
                        {
                            pc.setFishingReady( true );
                            pc.sendPackets(new S_Fishing());
                            pc.sendPackets( new S_PacketBox( S_PacketBox.FISHING ) );
                        }
                        else if ( currentTime > ( time + 1000 ) )
                        {
                            pc.setFishingTime( 0 );
                            pc.setFishingReady( false );
                            pc.setFishing( false );
                            pc.sendPackets( new S_CharVisualUpdate( pc ) );
                            pc.broadcastPacket( new S_CharVisualUpdate( pc ) );
                            pc.sendPackets( new S_ServerMessage( 1163, "" ) ); // 釣りが終了しました。
                            removeMember( pc );
                        }
                    }
                }
            }
        }
    }
}